package com.jhy.suixianglu.daima20221208;

/**
 * 二分查找
 */
public class Binarylookup {
    public static int search(int[] nums, int target) {
        /**
         * 这里使用左闭右开的原则
         */
        int left = 0;
        int right = nums.length;
        while (left < right) {
            int mid = left + ((right - left) >> 1);
            if (target > nums[mid]) {
                left = mid + 1;
            } else if (target < nums[mid]) {
                right = mid;
            } else {
                return mid;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] nums = {-1, 0, 3, 5, 9, 12};
        int tar = 9;
        int search = search(nums, tar);
        System.out.println(search);
    }
}